#include "Auth.h"
#include <regex>

namespace aod {

std::string Auth::ExtractSessionId(const httplib::Request& req) {
    // 从Authorization头中提取Bearer token
    if (req.has_header("Authorization")) {
        std::string auth_header = req.get_header_value("Authorization");
        std::regex bearer_regex("^Bearer\\s+(.+)$");
        std::smatch match;
        
        if (std::regex_match(auth_header, match, bearer_regex)) {
            return match[1].str();
        }
    }
    
    // 从Cookie中提取session_id
    if (req.has_header("Cookie")) {
        std::string cookie_header = req.get_header_value("Cookie");
        std::regex session_regex("session_id=([^;]+)");
        std::smatch match;
        
        if (std::regex_search(cookie_header, match, session_regex)) {
            return match[1].str();
        }
    }
    
    return "";
}

bool Auth::ValidateSession(const httplib::Request& req, Json::Value* user_info) {
    std::string session_id = ExtractSessionId(req);
    if (session_id.empty()) {
        return false;
    }
    
    return _session_table->ValidateSession(session_id, user_info);
}

// 管理员功能已移除，所有用户都有相同权限
bool Auth::IsAdmin(const Json::Value& user_info) {
    return true;  // 所有用户都被视为有权限
}

void Auth::SetAuthHeaders(httplib::Response& res, const std::string& session_id) {
    res.set_header("Set-Cookie", "session_id=" + session_id + "; HttpOnly; Path=/; Max-Age=86400");
}

void Auth::SetUnauthorizedResponse(httplib::Response& res) {
    Json::Value error_response;
    error_response["error"] = "Unauthorized";
    error_response["message"] = "Authentication required";
    
    Json::StreamWriterBuilder builder;
    std::string response_body = Json::writeString(builder, error_response);
    
    res.status = 401;
    res.set_content(response_body, "application/json");
}

void Auth::SetForbiddenResponse(httplib::Response& res) {
    Json::Value error_response;
    error_response["error"] = "Forbidden";
    error_response["message"] = "Insufficient permissions";
    
    Json::StreamWriterBuilder builder;
    std::string response_body = Json::writeString(builder, error_response);
    
    res.status = 403;
    res.set_content(response_body, "application/json");
}

bool RequireAuth(const httplib::Request& req, httplib::Response& res, Auth& auth, Json::Value* user_info) {
    if (!auth.ValidateSession(req, user_info)) {
        auth.SetUnauthorizedResponse(res);
        return false;
    }
    return true;
}

bool RequireAdmin(const httplib::Request& req, httplib::Response& res, Auth& auth, Json::Value* user_info) {
    if (!RequireAuth(req, res, auth, user_info)) {
        return false;
    }
    
    if (!auth.IsAdmin(*user_info)) {
        auth.SetForbiddenResponse(res);
        return false;
    }
    
    return true;
}

} 